package com.baba.bracelet.controller;

import com.alibaba.fastjson.JSONObject;
import com.baba.bracelet.entity.ReportPushEntity;
import com.baba.bracelet.service.ReportPushService;
import com.baba.bracelet.service.ReportStrategy;
import com.baba.bracelet.utils.SpringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wulongbo
 * @version 1.0
 * @date 2020/6/5 15:52
 * @description
 */
@RestController
@RequestMapping("/report")
@Api(tags = "消息推送模块")
public class PushController {

    @Autowired
    private ReportPushService reportPushService;

    @ApiOperation(value="消息上传推送接口", notes="设备有数据上传会立即调⽤指定HTTP接⼝")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "token", dataType = "String", required = true, value = "安全校验"),
            @ApiImplicitParam(paramType = "query", name = "content", dataType = "String", required = true, value = "JsonObject") })
    @RequestMapping("/pushMessage")
    public String restart(String token,String content) throws IOException {

        ReportPushEntity entity=null;
        JSONObject jsonObject =JSONObject.parseObject(content);
        //渠道id
        String channelId=jsonObject.get("type").toString();

        if (StringUtils.isEmpty(channelId)) {
//            return setResultError("channelId不能为空!");
            return "channelId不能为空!";
        }

        Map<String,Object> map = new HashMap<>();
        //kay是字段名 value是字段值
        map.put("channel_id",channelId);
        Collection<ReportPushEntity>  collection= reportPushService.listByMap(map);

        if(collection.size()==1){
             entity=collection.iterator().next();
        }
        if (entity == null) {
//            return setResultError("没有查询到该渠道信息");
            return "没有查询到该渠道信息";
        }

        String strategyBeanId=entity.getStrategyBeanId();

        if(StringUtils.isEmpty(strategyBeanId)){
//            return setResultError("没有配置策略BeanId");
            return "没有配置策略BeanId";
        }

        // 使用beanid从容器获取对象
        ReportStrategy reportStrategy= SpringUtil.getBean(strategyBeanId,ReportStrategy.class);

        return reportStrategy.execute();

    }

}
